import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, message, Input, Modal } from 'antd';
import moment from 'moment';
import { ProductGroupTreeC, PrimaryC, PrimaryGhostC, DATA_ENTRY, AdvancedSearch, TableC, ContentPackage, InputNumberC, InputC } from '../../../comps';
import { fixedNum } from '../../../../src/utils/utils.js';
import TransferModalC from './transferModalC';
import { isZiGuanEvir, exportFile } from '../../../utils/commonFunc';
import CashDepositModalC from './cashDepositModalC';

const { TextArea } = Input;
const FormItem = Form.Item;
@connect(({ fundManageNewM, userM: user, loading, positionInquiryM, availableAssetM }) => ({
  fundManageNewM,
  currentUser: user.currentUser,
  tableLoading: loading.effects['fundManageNewM/fetch'],
  operationLoading: loading.effects['fundManageNewM/operation'],
  transferLoading: loading.effects['fundManageNewM/transfer'],
  cashDepositLoading: loading.effects['fundManageNewM/transfer'],
  positionInquiryM,
  availableAssetM,
}))
@Form.create()
export default class Fund extends PureComponent {
  state = {
    rowData: {},
    checkDisable: {},
    pageSize: '10',
    operationVisible: false,
    modalVisible: false,
    cashDepositVisible: false, // 保证金管理模态框
    operationType: '',
    maximum: null,
    outAccount: {},
    inAccount: {},
    isReset: false, //判断是否点击重置
    currentPage: 1, //页码
    numInPage: 10, //每页条数
    searchObj: {},
    transferMaximum: undefined, //划转资金限额
  };

  componentDidMount() {
    //
    this.props.dispatch({
      type: 'fundManageNewM/fetchDict',
      payload: ['PMS_FUND_OPERATION'],
    });
    // 查询列表
    this.queryTableList();
  }
  // 表格数据格式处理
  formatterData = (value) => {
    if (value === 0) {
      return value;
    } else if (value === null) {
      return '--';
    } else {
      return fixedNum(Number(value));
    }
  };
  // 操作按钮点击事件
  fundOperation = (type) => {
    const { rowData } = this.state;
    let maximum = null;
    if (type === '0') maximum = 99999999999;
    if (type === '1') maximum = rowData.currentFundBalance || 0;
    if (type === '2') maximum = rowData.tZeroAvailableFund || 0;
    if (type === '3') maximum = (rowData.freezingFundBalance || 0) - (rowData.thawFundBalance || 0);
    if (type === '4') maximum = rowData.freezingFundBalance || 0;
    if (type === '5') maximum = rowData.thawFundBalance || 0;
    this.setState({
      maximum,
      operationType: type,
      operationVisible: true,
    });
  };

  // 划入组合   下拉change事件
  selectInAccount = (value) => {
    if (value) {
      this.setState({
        inAccount: value,
      });
    } else {
      this.setState({
        inAccount: { key: undefined },
      });
    }
  };
  // 划出组合   下拉change事件
  selectOutAccount = (value) => {
    if (value) {
      this.props.dispatch({
        type: 'availableAssetM/getFund',
        payload: {
          nodeId: value.key,
        },
        callback: (data) => {
          if (data) {
            this.setState({
              transferMaximum: data[0]?.tzeroAvailableFund,
            });
          } else {
            this.setState({
              transferMaximum: undefined,
            });
          }
        },
      });
    } else {
      this.setState({
        transferMaximum: undefined,
      });
    }
  };

  // 资金划转模态框的显示隐藏
  changeModalVisible = (msg) => {
    this.setState({
      modalVisible: msg,
    });
  };
  // 资金划转模态框调用接口
  getResult = (flag) => {
    if (flag) {
      this.props.dispatch({
        type: 'fundManageNewM/fetch',
        payload: {
          params: this.state.searchObj,
          current: this.state.currentPage,
          pageSize: this.state.numInPage,
        },
      });
    }
  };
  // 资金减少时发生金额的校验
  handleValidator = (rule, val, callback) => {
    if (val > this.state.maximum) {
      callback('发生金额不能大于限额！');
    }
    callback();
  };
  // 其他操作模态框
  renderOperationModal() {
    const that = this;
    const { operationVisible, operationType, rowData, maximum } = this.state;
    const {
      fundManageNewM,
      form: { getFieldDecorator, getFieldValue },
      dispatch,
      currentUser,
      operationLoading,
    } = this.props;
    const { dictMap } = fundManageNewM;
    const dict = (dictMap.PMS_FUND_OPERATION || []).filter((item) => operationType === item.code);
    const modalProps = {
      destroyOnClose: true,
      visible: operationVisible,
      maskClosable: false,
      title: (dict[0] || { value: '' }).value,
      width: 900,
      okText: '提交',
      okButtonProps: { loading: operationLoading },
      onOk() {
        // 操作提交了
        const amount = getFieldValue('amount');
        if (amount === '0') {
          message.error('请填写有效金额');
          return;
        }
        dispatch({
          type: 'fundManageNewM/operation',
          payload: {
            code: rowData.combCode,
            name: rowData.combName,
            type: operationType,
            amount: `${amount}`,
            operateBy: isZiGuanEvir() ? isZiGuanEvir()['iv-user'] : localStorage.getItem('antd-pro-userId'),
          },
        }).then((res) => {
          if (res && res.success) {
            message.success('资金操作成功');
            that.setState({
              operationVisible: false,
              checkDisable: true,
            });
            that.props.dispatch({
              type: 'fundManageNewM/fetch',
              payload: {
                params: that.state.searchObj,
                current: that.state.currentPage,
                pageSize: that.state.numInPage,
              },
            });
          } else {
            message.error('资金操作失败');
          }
        });
      },
      onCancel() {
        that.setState({
          operationVisible: false,
        });
      },
    };
    const formItemLayout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    };
    const formItemLayouts = {
      labelCol: {
        span: 3,
      },
      wrapperCol: {
        span: 18,
      },
    };
    return (
      <Modal {...modalProps}>
        <div>
          <Form>
            <Row style={{ marginBottom: '10px' }}>
              <Col span={12}>
                <ProductGroupTreeC
                  form={this.props.form}
                  formItemLayout={formItemLayout}
                  title={'产品组合'}
                  dataIndex='comb'
                  disabled={true}
                  multiple={false}
                  initialValue={rowData.portfolioId || ''}
                />
              </Col>
              <Col span={12}>
                <InputC form={this.props.form} dataIndex={'moneyType'} title={'币种'} formItemLayout={formItemLayout} initialValue={'人民币'} disabled={true} />
              </Col>
            </Row>
            <Row style={{ marginBottom: '10px' }}>
              {this.state.operationType == '0' ? (
                ''
              ) : (
                <Col span={12}>
                  <InputNumberC
                    dataIndex='amount2'
                    title={'限额(元)'}
                    precision={2}
                    splitStyle={true}
                    form={this.props.form}
                    formItemLayout={formItemLayout}
                    initialValue={maximum || undefined}
                    disabled={true}
                  />
                </Col>
              )}

              {this.state.operationType == '1' ? (
                <Col span={12}>
                  <InputNumberC
                    dataIndex='amount'
                    title={'发生金额'}
                    precision={2}
                    min={0}
                    rules={[{ validator: this.handleValidator }, { required: true, message: '请填写发生金额' }]}
                    placeholder='请填写金额(元)(必填)'
                    splitStyle={true}
                    form={this.props.form}
                    formItemLayout={formItemLayout}
                  />
                </Col>
              ) : (
                <Col span={12}>
                  <InputNumberC
                    dataIndex='amount'
                    title={'发生金额'}
                    precision={2}
                    min={0}
                    max={maximum < 0 ? 0 : maximum}
                    rules={[{ required: true, message: '请填写发生金额' }]}
                    placeholder='请填写金额(元)(必填)'
                    splitStyle={true}
                    form={this.props.form}
                    formItemLayout={formItemLayout}
                  />
                </Col>
              )}
            </Row>
            <Row style={{ marginBottom: '10px' }}>
              <Col span={24}>
                <FormItem label='备注' {...formItemLayouts}>
                  {getFieldDecorator('remark', {})(<TextArea placeholder='' />)}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
      </Modal>
    );
  }
  // 资金划转模态框
  renderTransferModal() {
    const that = this;
    const { modalVisible, transferMaximum } = this.state;
    const { currentUser, transferLoading } = this.props;
    const modalProps = {
      destroyOnClose: true,
      visible: modalVisible,
      maskClosable: false,
      title: '资金划转',
      width: 900,
      okText: '提交',
      okButtonProps: { loading: transferLoading },
      onCancel() {
        that.setState({
          modalVisible: false,
        });
      },
    };
    return (
      <TransferModalC
        modalProps={modalProps}
        maximum={transferMaximum}
        selectOutAccount={this.selectOutAccount}
        selectInAccount={this.selectInAccount}
        changeModalVisible={this.changeModalVisible}
        getResult={this.getResult}
        currentUser={currentUser}
      />
    );
  }
  // 保证金管理模态框
  renderCashDeposit() {
    const that = this;
    const { cashDepositVisible, rowData } = this.state;
    const { currentUser, cashDepositLoading } = this.props;
    const modalProps = {
      destroyOnClose: true,
      visible: cashDepositVisible,
      maskClosable: false,
      title: '保证金管理',
      width: 900,
      okText: '提交',
      okButtonProps: { loading: cashDepositLoading },
      onCancel() {
        that.setState({
          cashDepositVisible: false,
        });
      },
    };
    return (
      <CashDepositModalC
        modalProps={modalProps}
        changeModalVisible={(e) => {
          that.setState({
            cashDepositVisible: e,
          });
        }}
        rowData={rowData}
        getResult={that.getResult}
      />
    );
  }

  // 导出
  exprot = () => {
    const { currentUser } = this.props;
    const { searchObj } = this.state;
    const params = {};
    params.userId = isZiGuanEvir() ? isZiGuanEvir()['iv-user'] : localStorage.getItem('antd-pro-userId');
    params.search_NOTNULL_accountFlag = '1';
    params.search_INLIST_portfolioCode = searchObj.search_INLIST_portfolioCode ? searchObj.search_INLIST_portfolioCode.join() : undefined;
    params.startDate = searchObj.startDate ? searchObj.startDate : undefined;
    exportFile('api/v1/fundAccount/export', params);
  };

  // 表格查询事件
  queryTableList = (e) => {
    let tempObj = {};
    if (JSON.stringify(e) == '{}' || !e) {
      tempObj.startDate = moment().format('YYYYMMDD');
    } else {
      for (let k in e) {
        if (k == 'startDate') {
          tempObj[k] = e[k].format('YYYYMMDD');
          continue;
        }
        tempObj[k] = e[k];
      }
    }
    this.setState({
      checkDisable: {},
    });
    tempObj.userId = isZiGuanEvir() ? isZiGuanEvir()['iv-user'] : localStorage.getItem('antd-pro-userId');
    tempObj.search_NOTNULL_accountFlag = '1';
    this.setState(
      {
        searchObj: tempObj,
        isReset: false,
      },
      () => {
        this.props.dispatch({
          type: 'fundManageNewM/fetch',
          payload: {
            params: this.state.searchObj,
            current: this.state.currentPage,
            pageSize: this.state.numInPage,
          },
        });
      },
    );
  };

  // 表格change事件
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this,
        this.setState({
          isReset: false,
        });
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.props.dispatch({
          type: 'fundManageNewM/fetch',
          payload: {
            params: this.state.searchObj,
            current: this.state.currentPage,
            pageSize: this.state.numInPage,
          },
        });
      },
    );
  };
  render() {
    const that = this;
    const { rowData, checkDisable } = this.state;
    const { fundManageNewM, tableLoading } = this.props;
    const {
      list: { data, pagination },
      dictMap,
    } = fundManageNewM;
    const columns = [
      {
        title: '日期',
        dataIndex: 'dataDt',
        key: 'dataDt',
        width: 120,
        render: (text, record, index) => {
          if (text === null || text === undefined) {
            return '--';
          } else {
            return text.substring(0, 4) + '-' + text.substring(4, 6) + '-' + text.substring(6, 8);
          }
        },
      },
      {
        title: '产品代码',
        dataIndex: 'portfolioCode',
        key: 'portfolioCode',
        width: 180,
      },
      {
        title: '产品名称',
        dataIndex: 'portfolioName',
        key: 'portfolioName',
        width: 200,
      },
      {
        title: '组合代码',
        dataIndex: 'combCode',
        key: 'combCode',
        width: 180,
      },
      {
        title: '组合名称',
        dataIndex: 'combName',
        key: 'combName',
        width: 200,
      },
      {
        title: '期初现金余额',
        dataIndex: 'initialFundBalance',
        key: 'initialFundBalance',
        align: 'right',
        width: 120,
        render: (value) => this.formatterData(value),
      },
      {
        title: '当前现金余额',
        dataIndex: 'currentFundBalance',
        key: 'currentFundBalance',
        align: 'right',
        width: 120,
        render: (value) => this.formatterData(value),
      },
      {
        title: 'T+0交易可用',
        dataIndex: 'tZeroAvailableFund',
        key: 'tZeroAvailableFund',
        align: 'right',
        width: 120,
        render: (value) => this.formatterData(value),
      },
      {
        title: 'T+1交易可用',
        dataIndex: 'tOneAvailableFund',
        key: 'tOneAvailableFund',
        align: 'right',
        width: 120,
        render: (value) => this.formatterData(value),
      },
      {
        title: 'T+2交易可用',
        dataIndex: 'ttwoAvailableFund',
        key: 'ttwoAvailableFund',
        align: 'right',
        width: 120,
        render: (value) => this.formatterData(value),
      },
      {
        title: '冻结金额',
        dataIndex: 'freezingFundBalance',
        key: 'freezingFundBalance',
        align: 'right',
        width: 120,
        render: (value) => this.formatterData(value),
      },
      {
        title: '解冻金额',
        dataIndex: 'thawFundBalance',
        key: 'thawFundBalance',
        align: 'right',
        width: 120,
        render: (value) => this.formatterData(value),
      },
      {
        title: '期货保证金余额',
        dataIndex: 'totalMargin',
        key: 'totalMargin',
        align: 'right',
        width: 120,
        render: (value) => this.formatterData(value),
      },
      {
        title: '期货保证金可用',
        dataIndex: 'availableMargin',
        key: 'availableMargin',
        align: 'right',
        width: 120,
        render: (value) => this.formatterData(value),
      },
      {
        title: '币种',
        dataIndex: 'currency',
        key: 'currency',
        width: 100,
      },
    ];
    const formItemLayout = {
      labelCol: {
        xs: { span: 7, offset: 0 },
        sm: { span: 11, offset: 0 },
        md: { span: 11, offset: 0 },
        lg: { span: 11, offset: 0 },
        xl: { span: 10, offset: 0 },
        xxl: { span: 8, offset: 0 },
      },
      wrapperCol: {
        xs: { span: 15, offset: 0 },
        sm: { span: 11, offset: 0 },
        md: { span: 11, offset: 0 },
        lg: { span: 11, offset: 0 },
        xl: { span: 12, offset: 0 },
        xxl: { span: 14, offset: 0 },
      },
    };
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'search_INLIST_portfolioCode',
          title: '产品组合',
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          allowClear: true,
          formItemLayout: formItemLayout,
          treeCheckable: isZiGuanEvir() ? true : false,
        },
        {
          dataIndex: 'startDate',
          title: '日期',
          type: DATA_ENTRY.SINGLEDATE,
          initialValue: moment(),
          formItemLayout: formItemLayout,
        },
      ],
      //点击查询按钮
      onQuery: (e) => {
        this.queryTableList(e);
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          searchObj: {},
          isReset: true,
        });
      },
    };
    return (
      <ContentPackage
        title='资金管理'
        contentHtml={
          <div>
            <AdvancedSearch {...searchProps} />

            <div style={{ margin: '10px 0' }}>
              {(dictMap.PMS_FUND_OPERATION || []).map((item, index) => {
                if (item.code !== '6') {
                  return (
                    <PrimaryC
                      key={index}
                      disabled={!checkDisable || !checkDisable.operationPermission}
                      onClick={() => this.fundOperation(item.code)}
                      title={item.value}
                      style={{ margin: '0 4px' }}
                    />
                  );
                } else {
                  return '';
                }
              })}
              <PrimaryC
                disabled={!checkDisable || !checkDisable.operationPermission}
                onClick={() => that.setState({ modalVisible: true })}
                title={'资金划转'}
                style={{ margin: '0 4px' }}
              />
              <PrimaryC
                disabled={!checkDisable || !checkDisable.operationPermission}
                onClick={() => that.setState({ cashDepositVisible: true })}
                title={'保证金管理'}
                style={{ margin: '0 4px' }}
              />
              <PrimaryGhostC onClick={this.exprot} title={'导出'} style={{ float: 'right' }} />
            </div>
            {this.renderOperationModal()}
            {this.renderTransferModal()}
            {this.renderCashDeposit()}
            <TableC
              onRow={(record, index) => {
                return {
                  onClick: (e) => {
                    this.props
                      .dispatch({
                        type: 'fundManageNewM/findPermission',
                        payload: record.portfolioId,
                      })
                      .then((res) => {
                        that.setState({
                          checkDisable: res,
                        });
                      });
                    that.setState({
                      rowData: record,
                    });
                  },
                };
              }}
              rowClassName={(record) => {
                return record.key === rowData.key ? 'trade-select' : '';
              }}
              rowKey='key'
              loading={tableLoading}
              columns={columns}
              current={pagination && pagination.current}
              total={pagination && pagination.total}
              pageSize={pagination && pagination.pageSize}
              dataSource={data}
              scroll={{ x: 'max-content' }}
              selfScrollY={true}
              onChange={this.handleTableChange}
            />
          </div>
        }
      />
    );
  }
}
